/**
 * @ Author: luoqi
 * @ Create Time: 2024-07-22 21:57
 * @ Modified by: luoqi
 * @ Modified time: 2025-04-08 16:57
 * @ Description:
 */

#include <bsp.h>
#include <stdbool.h>
#include <stdlib.h>
#include "boot/qboot.h"
#include "init.h"
#include "mem/flash.h"
#include "qshell/qterm.h"

static QCliCmd _cmd_rb;
static bool _isboot = false;

static QCliCmd _cmd_jmp;
static int _cmd_jmp_hdl(int argc, char **argv)
{
    if(argc == 1) {
        qboot_jump(QBOOT_APP_ADDR);
    } else {
        return -1;
    }
    return 0;
}
static int _cmd_boot_hdl(int argc, char **argv)
{
    if(argc == 1) {
        _isboot = true;
    } else {
        _isboot = false;
    }
    return 0;
}

static inline int _send(const uint8_t *data, uint32_t sz)
{
    return bsp_uart1_send(data, sz, 100);
}

int boot_init(void)
{
    qterm_attach(&_cmd_rb, "rb", _cmd_boot_hdl, "remote call firmware update");
    qterm_attach(&_cmd_jmp, "jmp", _cmd_jmp_hdl, "jump to app");
    qboot_init(_send, bsp_uart1_recv, flash_write, flash_erase);

    return 0;
}

int main(void)
{
    uint8_t c;
    app_init();
    boot_init();

    flash_read(QBOOT_ISBOOT_ADDR, &c, 1);
    if(c == 0x51) {
        uint8_t flag;
        if(bsp_uart1_recv(&flag, 1, 500) == 1) {
            if(flag == 27) { // ESC
                flash_erase(QBOOT_ISBOOT_ADDR, 1);
            }
        } else {
            qboot_jump(QBOOT_APP_ADDR);
        }
    }

    while(1) {
        if(_isboot) {
            if(qboot_exec() < 0) {
                _isboot = false;
            }
        } else {
            if(bsp_uart1_recv(&c, 1, 0) == 1) {
                qterm_exec(c);
            }
        }
    }

    return 0;
}
